package com.xs.ahoi.hcxs.ui.dialog;

import android.content.Context;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.utils.FileUtil;
import com.xs.ahoi.hcxs.utils.StringUtils;

/**
 * author: cdfuhuichao
 * date: 2019/7/18 16:22
 * path: com.xs.ahoi.hcxs.ui.dialog.DialogChangeFileName
 * description: 修改文件名弹框
 */
public class DialogChangeFileName extends BaseDialog {

    @BindView(R.id.etInput)
    public EditText etInput;
    @BindView(R.id.tvTip)
    public TextView tvTip;

    private String path;
    private String name;

    private String exist = "当前目录已存在相同名称，请重新输入";
    private String empty = "文件名不能为空！";

    private ChangeFilename changeFilename;

    public DialogChangeFileName(Context context) {
        super(context, R.style.common_dialog);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_change_filename;
    }

    @Override
    protected int showPosition() {
        return Gravity.CENTER;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        etInput.setText(name);
        etInput.setSelection(name.length());
    }

    public void show(String filename, String path) {
        this.path = path;
        this.name = filename.replace(".txt", "");
        show();
    }

    @OnClick({R.id.tvDialogOk, R.id.tvDialogCancel})
    public void onClick(View v) {
        switch (v.getId()) {
            // 确认
            case R.id.tvDialogOk:
                String newFilename = etInput.getText().toString() + ".txt";
                if (StringUtils.isEmpty(newFilename)) {
                    tvTip.setText(empty);
                    break;
                }

                // 重命名
                Pair<Boolean, String> pair = FileUtil.rename(path, newFilename);
                if (pair.first) {
                    changeFilename.success(pair.second, newFilename);
                    dismiss();
                } else {
                    tvTip.setText(exist);
                }
                break;
            // 取消
            case R.id.tvDialogCancel:
                dismiss();
                break;
        }
    }

    public void setListener(ChangeFilename changeFilename) {
        this.changeFilename = changeFilename;
    }

    public interface ChangeFilename {
        void success(String newPath, String newFilename);
    }
}
